package de.dhbw.asa.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import de.dhbw.asa.controller.DatabaseBean;

/**
 * This class provides all the stuff we need for a Database Connection
 * @author aar
 *
 */

@ManagedBean
@SessionScoped
public class Database 
{
	
	@ManagedProperty(value = "#{databaseBean}")
	DatabaseBean databaseBean;
	
	Connection jConnection;
	Statement jStatement;
	String sDatabaseName="jdbc:mysql://localhost:3306/webshop";
	String sUser="shopadmin";
	String sPassword="admin";

	/*
	 * this method creates a Database Connection
	 */
	public boolean createConnection()
	{
		if (databaseBean!=null)
		{
			this.sDatabaseName=databaseBean.getsDatabaseName();
			this.sUser=databaseBean.getsUser();
			this.sPassword=databaseBean.getsPassword();
		}
		System.out.println("Datenbankaufbau mit:");
		System.out.println(this.sDatabaseName);
		System.out.println(this.sUser);
		System.out.println(this.sPassword);
		
		boolean bReturn = false;
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			jConnection = DriverManager.getConnection(this.sDatabaseName, this.sUser, this.sPassword);
			jStatement = jConnection.createStatement();
			// Connection was created sucessfully
			bReturn = true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return bReturn;
	}
	
	/*
	 * this method closes a given Connection
	 */
	public boolean closeConnection()
	{
		boolean bReturn = false;
		try
		{
			jConnection.close();
			// Connection was closed sucessfully
			bReturn = true;
			jStatement = null;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return bReturn;
	}
	
	/*
	 * this method executes a SQLQuery
	 */
	public ResultSet executeQuery(String sQuery)
	{
		ResultSet rsReturn = null;
		try
		{
			System.out.println("Setze folgenden Abfrage ab: "+sQuery);
			rsReturn = jStatement.executeQuery(sQuery);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return rsReturn;
	}
	
	public void execute(String sQuery)
	{
		try
		{
			System.out.println("Setze folgenden Befehl ab: "+sQuery);
			jStatement.execute(sQuery);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public DatabaseBean getDatabaseBean() {
		return databaseBean;
	}

	public void setDatabaseBean(DatabaseBean databaseBean) {
		this.databaseBean = databaseBean;
	}
	
}
